package org.example.com.service.impl;
import io.jsonwebtoken.Claims;

import org.example.com.config.JwtConfig;
import org.example.com.service.SeckillServcice;
import org.example.com.util.JsonResult;
import org.example.com.util.RecultTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SeckillServiceImpl implements SeckillServcice {
    private StringRedisTemplate stringRedisTemplate;
    private Date date=new Date(124,9,27,11,45,30);
    private String bookId="152144078216750661";
    private String money="81.6";
    @Autowired
    public SeckillServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate=stringRedisTemplate;
        ListOperations<String, String> list=stringRedisTemplate.opsForList();
        stringRedisTemplate.delete("SEC_KILL_LIST");
        stringRedisTemplate.delete("SEC_KILL");
        list.rightPush("SEC_KILL_LIST","aaa");
        list.rightPush("SEC_KILL_LIST","aaa");
        list.rightPush("SEC_KILL_LIST","aaa");
    }


    @Override
    public JsonResult seckill(String token) {
        HashOperations<String, Object, Object> hashOperations=stringRedisTemplate.opsForHash();
        ListOperations<String, String> listOperations=stringRedisTemplate.opsForList();
        Claims claims= JwtConfig.parseJWT(token);
        String userId=claims.get("id").toString();
        Date nowDAte=new Date();
        if (nowDAte.before(date)){
            return RecultTool.fail(5009,"秒杀没有开始");
        }
        Object val=hashOperations.get("SEC_KILL",userId);
        if (val!=null){
            return RecultTool.fail(5008,"一次只能秒杀一件物品");
        }
        Long size=listOperations.size("SEC_KILL_LIST");
        if (size==null || size==0){
            return RecultTool.fail(5007,"秒杀已经结束");
        }
        stringRedisTemplate.watch("SEC_KILL_LIST");
        SessionCallback<List<Object>> sessionCallback=new SessionCallback<List<Object>>() {
            @Override
            public <K, V> List<Object> execute(RedisOperations<K, V> operations) throws DataAccessException {
                stringRedisTemplate.multi();
                hashOperations.put("SECKILL",userId,"1");
                listOperations.rightPop("SEC_KILL_LIST");
                return stringRedisTemplate.exec();
            }
        };
        List<Object> exec=stringRedisTemplate.execute(sessionCallback);
        if (exec.size()==0 || exec.get(0)==null){
            return RecultTool.fail(5006,"秒杀失败");
        }
        JsonResult success=RecultTool.success(bookId);
        success.setError(money);
        return success;
    }
}
